/**
 * 
 */
package anonymouschat.service;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import anonymouschat.messages.ServerAnnounceMessage;
import anonymouschat.messages.clientrequests.UserLoginRequest;
import anonymouschat.messages.clientrequests.encryptedMessageWrapperMessage;


/**
 * Runs the code for a server in the anonymous chat system Launch with main
 * method with the server's number as the argument (listens on port 7000 + srv#)
 * 
 * @author Jonathan Mandeville
 * 
 */

public class Server extends Thread
{

    // XXX: these should all be changed to ConcurrentHashMap, HashTables are
    // out-dated
    // XXX: these should all be volatile; simply declaring them as static does
    // NOT ensure that all threads will see most recent values

    // public static Hashtable<String, ArrayList<String>> chatroomMemberList =
    // new Hashtable<String, ArrayList<String>>();
    public static volatile ConcurrentMap<String, ArrayList<String>> chatroomMemberList = new ConcurrentHashMap<String, ArrayList<String>>();

    // public static Hashtable<String, OutConnection> currentUserConnections =
    // new Hashtable<String, OutConnection>();
    //public static volatile ConcurrentMap<String, OutConnection> currentUserConnections = new ConcurrentHashMap<String, OutConnection>();

    // public static Hashtable<String, OutConnection> currentServerConnections =
    // new Hashtable<String, OutConnection>();

    public static volatile ConcurrentMap<String, OutConnection> currentConnections = new ConcurrentHashMap<String, OutConnection>();

    public static volatile ConcurrentMap<String, String> connectionMap;
    
    private static String serverName = "";
    
    public static ServerIdentObject Identity;

    private static int port = -1;
    
    public static SecureRandom rand;

    /**
     * 
     * @param name
     *            the server name
     * @param portno
     *            the port to use for accepting connections
     */
    public Server( String name, int portno ) {
        serverName = name;
        port = portno;
        
    }

    /**
     * @param args
     */
    public static void main( String[] args ) {
        // Initial implementation uses arguments for server names
    	rand = new SecureRandom();
        if( args.length > 1 ) {
            Server s = new Server( args[0], Integer.parseInt( args[1] ) );
            s.start();
            // ConstantVariables.serverListeningPort += Integer.parseInt(
            // args[0] );
        } else {
            System.out
                    .println( "You need to provide a name and port for this server" );
            System.exit( 0 );
        }
    }

    public static String getServerName() {
        return serverName;
    }

    private static ServerSocket serverSocket;

    /**
     * Run server thread (open new socket and listen for announce messages)
     */
    public void run() {
        serverSocket = null;

        try {
        	
        	if (ServerIdentObject.identityExists(serverName))
        		Identity = ServerIdentObject.loadIdentity(serverName);
        	else
        		Identity = new ServerIdentObject(serverName);
        	
            serverSocket = new ServerSocket( port );
            System.out.println( serverName + ": Listening on port " + port );
        } catch( UnknownHostException h ) {
            h.printStackTrace();
            System.exit( 1 );
        } catch( IOException e ) {
            e.printStackTrace();
            System.exit( 1 );
        } catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        while( true ) {
            try {
                listenForMessage();
            } catch( Exception e ) {
                e.printStackTrace();
                continue;
            }
        }
    }

    /**
     * Wait for an announce message, when received store the connection and
     * return
     * 
     * @throws Exception
     */
    public void listenForMessage() throws Exception {

        Socket clientSocket = null;
        try {
            clientSocket = serverSocket.accept();
            clientSocket.setKeepAlive( true );
        } catch( IOException e ) {
            System.err.println( "Accept failed." );
        }

        ObjectInputStream in = null;
        Object message = null;
        try {
            in = new ObjectInputStream( clientSocket.getInputStream() );
        } catch( IOException e ) {
            e.printStackTrace();
        }
        
       
        
        //connectionMap.put(key, value)
        OutConnection newOutConnection = new OutConnection( clientSocket, "" );
        //Server.currentConnections.put( connectionID, newOutConnection );
        //System.out.println( "Note: New client/server connection" );

        InConnectionThread newInConnection = new InConnectionThread(clientSocket, in, newOutConnection.getOutputStream());
        newInConnection.start();
        
        /*
        try {
            message = (Object) in.readObject();
        } catch( IOException e ) {
            e.printStackTrace();
        } catch( ClassNotFoundException e ) {
            e.printStackTrace();
        }

        // check for type of message
        if( message instanceof UserLoginRequest ) {
            UserLoginRequest req = (UserLoginRequest) message;

            OutConnection newOutConnection = new OutConnection( clientSocket,
                    req.getUserID() );
            Server.currentUserConnections.put( req.getUserID(),
                    newOutConnection );
            System.out.println( "Note: New user connection" );

            InConnectionThread newInConnection = new InConnectionThread(
                    clientSocket, in, newOutConnection );
            newInConnection.start();

        } else if( message instanceof ServerAnnounceMessage ) {
            ServerAnnounceMessage req = (ServerAnnounceMessage) message;

            OutConnection newOutConnection = new OutConnection( clientSocket,
                    req.getName() );
            Server.currentServerConnections.put( req.getName(),
                    newOutConnection );
            System.out.println( "Note: New server connection" );

            InConnectionThread newInConnection = new InConnectionThread(
                    clientSocket, in, newOutConnection );
            newInConnection.start();

        } else {
            System.err
                    .println( "Message object received is not of type AnnounceMessage from "
                            + clientSocket.getInetAddress()
                            + ":"
                            + clientSocket.getPort() );
        } */

    }

    public static int getServerPort()
    {
    	return port;
    }
    
}
